package com.hundsun.yr.universal.p2p.ui.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.adapter.HolderAdapter;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper.UpdateItem;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils.NetType;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSLoadMoreListView;
import com.hundsun.yr.universal.library.widget.HSLoadMoreListView.OnLoadMoreListener;
import com.hundsun.yr.universal.library.widget.HSSwipeRefreshLayout;
import com.hundsun.yr.universal.p2p.bean.BankRecord;
import com.hundsun.yr.universal.p2p.bean.BankStatementBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.BankRecordPresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.view.base.BaseListView;
import com.hundsun.yr.universal.p2p.widget.ValidateButton;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * @version V1.0
 * @Title: BankRecordActivity.java
 * @Description: 银行流水--改过
 * @date 2016-1-27 下午4:02:14
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class BankRecordActivity extends BaseActivity implements BaseListView, UpdateItem<BankStatementBeen>, OnLoadMoreListener,
        OnRefreshListener, OnClickListener {

    /**
     * 适配器
     **/
    private HolderAdapter<BankStatementBeen> mAdapter = null;
    /**
     * 上拉列表（listView）
     **/
    private HSLoadMoreListView loadMoreListView = null;
    /**
     * 下拉容器
     **/
    private HSSwipeRefreshLayout hsSwipeRefreshLayout = null;
    /**
     * 索引偏移量
     **/
    private int start = 0;
    /**
     * 数据集合
     **/
    private List<BankStatementBeen> data = new ArrayList<BankStatementBeen>();
    /**
     * 请求接口
     **/
    private RequestPresenter mPresenter = null;
    /**
     * 验证弹窗
     */
    public Dialog validate_dialog = null;
    /**
     * 验证码按钮
     */
    private ValidateButton btn_validate = null;
    /**
     * 验证码输入框
     */
    private EditText et_code = null;
    /**
     * 验证码
     */
    private String code = "";
    /**
     * 验证码类型
     */
    private int type = 0;
    private String zwgt_data;

    @Override
    protected boolean isApplyKitKatTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    protected int getContentViewLayoutID() {
        // TODO Auto-generated method stub
        return R.layout.act_bank_record;
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
        // TODO Auto-generated method stub

    }

    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        hsSwipeRefreshLayout = findView(R.id.hsSwipeRefreshLayout);
        return hsSwipeRefreshLayout;
    }


    /**
     * 加载数据
     */
    private void loadingData() {
        //swiprefresh的加载显示
        hsSwipeRefreshLayout.setRefreshing(true);
        start = 0;
        zwgt_data = BaseRequestTool2.getFormatedDateString();
		mPresenter.loadingData(TaskConstants.TASK_BILL,getString(R.string.root_url_test) + getString(R.string.api_user_test) +
                TaskConstants.TASK_BILL, Constants.EVENT_REFRESH_DATA, BaseRequestTool2.getHearder(mContext,TaskConstants.TASK_GET,
                getString(R.string.api_user_test) + TaskConstants.TASK_BILL,sharedPreferences.getShareProf(UserInfo.USER_NO),
                sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data),true);
    }

    @Override
    protected void initViewsAndEvents() {
        // TODO Auto-generated method stub
        setToolbarTitle(R.string.bank_record);

        loadMoreListView = findView(R.id.loadMoreListView);
        ViewCreatorHelper<BankStatementBeen> creatorHelper = new ViewCreatorHelper<BankStatementBeen>(R.layout.item_bank_record, this);
        mAdapter = new HolderAdapter<BankStatementBeen>(mContext, creatorHelper.viewCreator());

        loadMoreListView.setAdapter(mAdapter);
        hsSwipeRefreshLayout.setOnRefreshListener(this);
        loadMoreListView.setOnLoadMoreListener(this);
        mPresenter = new BankRecordPresenterImpl(this, this, BankRecord.BASEKEY, new BankRecord());
        loadingData();

//        showValidateDialog();
    }

    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }

    @Override
    protected void onNetworkConnected(NetType type) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onNetworkDisConnected() {
        // TODO Auto-generated method stub

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        // TODO Auto-generated method stub
        return null;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void refreshItem(View view, int position, BankStatementBeen record) {
        /**标题**/
        TextView tv_title = findView(view, R.id.tv_title);
        tv_title.setText(record.describe);

        /**时间**/
        TextView tv_time = findView(view, R.id.tv_time);
        tv_time.setText(record.relDate);
        /**金额**/
        TextView tv_money = findView(view, R.id.tv_money);
        tv_money.setText(record.txAmount);

        /**余额**/
        TextView tv_balance = findView(view, R.id.tv_banlance);
        tv_balance.setText(getString(R.string.bank_balance,record.currBal));
       /* TextView tv_money = findView(view, R.id.tv_money);
        String money = record.getBillams() + "¥" + record.getBillamt().toString();
        if (TextUtils.equals(record.getBillams(), "-")) {
//			tv_money.setTextColor(getResources().getColor(R.color.primary_cl_1));
//			tv_money.setText("-¥"+record.getBillamt().toString());
            tv_money.setText(SpannableStringBuilderUtils.colorSpan(money, record.getBillams(), getResources().getColor(R.color.primary_cl_1)));
        } else {
//			tv_money.setTextColor(getResources().getColor(R.color.primary_cl_4));
//			tv_money.setText("+¥"+record.getBillamt().toString());
            tv_money.setText(SpannableStringBuilderUtils.colorSpan(money, record.getBillams(), getResources().getColor(R.color.primary_cl_4)));
        }*/

    }

    @Override
    public void onLoadMore() {
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.TASK_BILL,getString(R.string.root_url_test) + getString(R.string.api_user_test) +
                TaskConstants.TASK_BILL, Constants.EVENT_REFRESH_DATA, BaseRequestTool2.getHearder(mContext,TaskConstants.TASK_GET,
                getString(R.string.api_user_test) + TaskConstants.TASK_BILL,sharedPreferences.getShareProf(UserInfo.USER_NO),
                sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data),false);
    }

    @Override
    public void onRefresh() {
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.TASK_BILL,getString(R.string.root_url_test) + getString(R.string.api_user_test) +
                TaskConstants.TASK_BILL, Constants.EVENT_REFRESH_DATA, BaseRequestTool2.getHearder(mContext,TaskConstants.TASK_GET,
                getString(R.string.api_user_test) + TaskConstants.TASK_BILL,sharedPreferences.getShareProf(UserInfo.USER_NO),
                sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data),false);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> void refreshListData(List<T> result) {
        hsSwipeRefreshLayout.setRefreshing(false);
        if (result == null){
            return;
        }
        // TODO Auto-generated method stub

        loadMoreListView.onLoadMoreComplete();
        if (data.size() > 0) data.clear();
        if (result != null) {
            data.addAll((Collection<? extends BankStatementBeen>) result);
            loadMoreListView.setLoadMoreEnabled(result.size() == Constants.PAGESIZE_LARGE);
        }
        mAdapter.update(data);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> void addMoreListData(List<T> result) {
        // TODO Auto-generated method stub
        loadMoreListView.onLoadMoreComplete();
        if (result != null && result.size() > 0) {
            data.addAll((Collection<? extends BankStatementBeen>) result);
            loadMoreListView.setLoadMoreEnabled(result.size() == Constants.PAGESIZE_LARGE);
        } else {
            loadMoreListView.setLoadMoreEnabled(false);
        }
        mAdapter.update(data);
    }


    @Override
    public <T> void onFailure(String task_name) {
        // TODO Auto-generated method stub
        hsSwipeRefreshLayout.setRefreshing(false);
        loadMoreListView.onLoadMoreComplete();
        if (data.size() > 0) data.clear();
        loadMoreListView.setAdapter(mAdapter);
        mAdapter.update(data);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.tv_cancle:
                if (validate_dialog != null && validate_dialog.isShowing())
                    validate_dialog.dismiss();
                finish();
                break;
            case R.id.btn_validate:
                String user_id = sharedPreferences.getShareProf(UserInfo.JX_ACCOUNT_NO);
                String url = "/yun-billvcode?phone=" + sharedPreferences.getShareProf(UserInfo.MOBILE) + "&type=" + type;
                mPresenter.loadingData(TaskConstants.TASK_MSMCODE, "http://api.zwgt.com" + url, Constants.EVENT_PROGRESS, BaseRequestTool.getHearder(mContext, user_id, url), true);
                type = 1;
//			validate();
                break;
            case R.id.btn_sure:
                if (TextUtils.isEmpty(et_code.getText())) {
                    showToast("请输入查询码");
                    return;
                }
                code = et_code.getText().toString();
                if (validate_dialog != null && validate_dialog.isShowing()) {
                    validate_dialog.dismiss();
                    et_code.setText("");
                }
                user_id = sharedPreferences.getShareProf(UserInfo.JX_ACCOUNT_NO);
                String recordUrl = "/yun-bill?phone=" + sharedPreferences.getShareProf(UserInfo.MOBILE) +
                        "&vcode=" + code + "&trnn=" + start + "&inpd=" + start + "&inpt=" + start + "&reld=" + start;
                mPresenter.loadingData(TaskConstants.TASK_DATA, "http://api.zwgt.com" + recordUrl, Constants.EVENT_REFRESH_DATA, BaseRequestTool.getHearder(mContext, user_id, recordUrl), true);
//			select(start, Constants.EVENT_REFRESH_DATA, true);
                break;
            default:
                break;
        }
    }


    //SELECT
    /**
     * 查询记录
     * @param start
     * @param event_tag
     * @param isSwipeRefresh
     */
//	private void select(int start,int event_tag,boolean isSwipeRefresh){
//		code=et_code.getText().toString();
//		String user_id=sharedPreferences.getShareProf(UserInfo.JX_ACCOUNT_NO);
//		String recordUrl="/yun-bill";
//		String key=sharedPreferences.getShareProf(UserInfo.CERT_NO);
//		TreeMap<String, String> params =new TreeMap<String, String>();
//		params.put("phone", sharedPreferences.getShareProf(UserInfo.MOBILE));
//		params.put("vcode", code);
//		params.put("trnn", start+"");
//		params.put("inpd", start+"");
//		params.put("inpt", start+"");
//		params.put("reld", start+"");
//		Gson gson = new Gson();
//		String str_params=gson.toJson(params);
//		String timestamp =HsDateUtils.timeformat(HsDateUtils.farmat_date_1, new Date());
//		String sign=MD5Utils.getMD5String(timestamp+str_params);
//		String message= ZWGTUtils.replaceBlank(Des3Util.encode(str_params));
//		String results="{\"sign\":\""+sign+"\",\"timestamp\":\""+timestamp+"\",\"message\":\""+message+"\"}";
//		
//		String url="http://api.zwgt.com/yun-bill";
//		mPresenter.loadingData(TaskConstants.TASK_DATA, url, event_tag, results.getBytes(), BaseRequestTool.getHearder(mContext, user_id, recordUrl, key, BaseRequestTool.POST), isSwipeRefresh);
//		if(validate_dialog!=null&&validate_dialog.isShowing())validate_dialog.dismiss();
//	}

    /**
     * 验证码获取接口
     */
//	private void validate(){
//		TreeMap<String, String> params =new TreeMap<String, String>();
//		params.put("phone", sharedPreferences.getShareProf(UserInfo.MOBILE));
//		params.put("type", type+"");
//		
//		Gson gson = new Gson();
//		String str_params=gson.toJson(params);
//		String timestamp =HsDateUtils.timeformat(HsDateUtils.farmat_date_1, new Date());
//		String sign=MD5Utils.getMD5String(timestamp+str_params);
//		String message= ZWGTUtils.replaceBlank(Des3Util.encode(str_params));
//		String results="{\"sign\":\""+sign+"\",\"timestamp\":\""+timestamp+"\",\"message\":\""+message+"\"}";
//		String user_id=sharedPreferences.getShareProf(UserInfo.JX_ACCOUNT_NO);
//		String key=sharedPreferences.getShareProf(UserInfo.CERT_NO);
//		String recordUrl="/yun-billvcode";
//		String url="http://api.zwgt.com/yun-billvcode";
//		mPresenter.loadingData("GETCODE", url, Constants.EVENT_PROGRESS, results.getBytes(),BaseRequestTool.getHearder(mContext, user_id, recordUrl, key, BaseRequestTool.POST), true);
//		type=1;
//	}


    /**
     * 认证弹窗
     */
    @SuppressLint("InflateParams")
    private void showValidateDialog() {
        if (validate_dialog == null) {
            LayoutInflater inflater = LayoutInflater.from(this);
            View view = inflater.inflate(R.layout.view_bankrecord_dialog, null);
            btn_validate = findView(view, R.id.btn_validate);
            btn_validate.setOnClickListener(this);
            TextView tv_cancle = findView(view, R.id.tv_cancle);
            tv_cancle.setOnClickListener(this);
            TextView tv_mobile = findView(view, R.id.tv_mobile);
            tv_mobile.setText(sharedPreferences.getShareProf(UserInfo.MOBILE));
            et_code = findView(view, R.id.et_code);
            HSButton btn_sure = findView(view, R.id.btn_sure);
            btn_sure.setOnClickListener(this);
            // 新建对话框对象
            validate_dialog = new Dialog(this, R.style.TransparentDialog);
            validate_dialog.setCancelable(false);
            validate_dialog.setContentView(view);
            validate_dialog.show();
        } else {
            if (!validate_dialog.isShowing()) validate_dialog.show();
        }
    }

    @Override
    public <T> void initializeViews(String task_name, T data) {
        // TODO Auto-generated method stub

        if (validate_dialog != null && validate_dialog.isShowing()) validate_dialog.dismiss();

        if (TextUtils.equals(TaskConstants.TASK_MSMCODE, task_name)) {
            showToast("验证码发送成功");
            return;
        } else {
            if (validate_dialog != null && validate_dialog.isShowing()) validate_dialog.dismiss();
        }
    }

}
